import asyncio
import aiohttp
import json
import time

async def check_agent_status():
    """检查系统中Agent的状态"""
    print("\n=== 检查Agent状态 ===")
    
    # 检查文本QA服务是否正常运行
    text_qa_url = "http://localhost:8001/health"
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(text_qa_url, timeout=5) as response:
                print(f"文本QA服务健康检查状态码: {response.status}")
                print(f"文本QA服务响应: {await response.text()}")
    except Exception as e:
        print(f"文本QA服务不可用: {str(e)}")

async def test_direct_text_qa():
    """直接测试文本QA服务"""
    print("\n=== 直接测试文本QA服务 ===")
    text_qa_url = "http://localhost:8001/text_qa"
    
    qa_data = {
        "query": "什么是人工智能？",
        "top_k": 3
    }
    
    try:
        async with aiohttp.ClientSession() as session:
            async with session.post(text_qa_url, json=qa_data, timeout=10) as response:
                print(f"直接调用状态码: {response.status}")
                response_data = await response.json()
                print(f"直接调用响应: {json.dumps(response_data, ensure_ascii=False, indent=2)}")
    except Exception as e:
        print(f"直接调用失败: {str(e)}")

async def test_search_with_debug():
    """测试搜索API并添加调试信息"""
    print("\n=== 测试搜索API (调试模式) ===")
    search_url = "http://localhost:8000/api/v1/search"
    
    search_data = {
        "query_type": "text",
        "query": "什么是人工智能？",
        "top_k": 3,
        "debug": True
    }
    
    async with aiohttp.ClientSession() as session:
        try:
            async with session.post(search_url, json=search_data, timeout=30) as response:
                print(f"搜索API状态码: {response.status}")
                response_data = await response.json()
                print(f"搜索API响应: {json.dumps(response_data, ensure_ascii=False, indent=2)}")
        except Exception as e:
            print(f"搜索API调用失败: {str(e)}")
            import traceback
            traceback.print_exc()

async def main():
    print("=== 搜索系统诊断工具 ===")
    print(f"当前时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
    
    # 检查Agent状态
    await check_agent_status()
    
    # 直接测试文本QA服务
    await test_direct_text_qa()
    
    # 测试搜索API
    await test_search_with_debug()
    
    print("\n=== 诊断完成 ===")
    print("根据以上信息，我们可以确定系统中存在的实际问题")

if __name__ == "__main__":
    asyncio.run(main())
